package cn.jtfadmin.core.modules.sys.service.impl;

import cn.jtfadmin.base.lang.common.service.BaseService;
import cn.jtfadmin.base.lang.common.utils.AkUtils;
import cn.jtfadmin.core.modules.sys.domain.dto.SysEnvDTO;
import cn.jtfadmin.core.modules.sys.domain.entity.SysEnvEntity;
import cn.jtfadmin.core.modules.sys.service.SysEnvConfig;
import cn.jtfadmin.core.modules.sys.service.SysEnvActionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.validation.annotation.Validated;

import java.util.Collection;
import java.util.Optional;

/**
 * 系统环境实现类
 * @author jtf
 * @since 0.0.1
 */
@Service
@Validated
public class SysEnvActionServiceImpl implements SysEnvActionService, ApplicationListener<ContextRefreshedEvent> {

    @Autowired
    protected BaseService<SysEnvEntity> service;

    @Override
    public String getValue(String key) {
        Optional<SysEnvEntity> optional = service.findOneByField("key", key);
        if (optional.isPresent()) {
            SysEnvEntity envEntity = optional.get();
            if(StringUtils.hasText(envEntity.getValue())){
                return envEntity.getValue();
            }
            return envEntity.getDefaultValue();
        }
        return null;
    }

    @Override
    @Transactional
    public void onApplicationEvent(ContextRefreshedEvent event) {
        ApplicationContext applicationContext = event.getApplicationContext();
        String[] beanNamesForType = applicationContext.getBeanNamesForType(SysEnvConfig.class);
        for (String s : beanNamesForType) {
            SysEnvConfig bean = applicationContext.getBean(s, SysEnvConfig.class);
            Collection<SysEnvDTO> configs = bean.getConfig();
            if(!CollectionUtils.isEmpty(configs)){
                for (SysEnvDTO dto : configs) {
                    Optional<SysEnvEntity> optional = service.findOneByField("key", dto.getKey());
                    if(!optional.isPresent()){
                        SysEnvEntity sysEnvEntity = AkUtils.copyProperties(dto, SysEnvEntity.class);
                        service.save(sysEnvEntity);
                    }else {
                        SysEnvEntity envEntity = optional.get();
                        envEntity.setDescribe(dto.getDescribe());
                        envEntity.setDefaultValue(dto.getDefaultValue());
                        envEntity.setSort(dto.getSort());
                        service.save(envEntity);
                    }

                }

            }
        }

    }
}
